package com.uzhie.web.aop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.uzhie.web.anno.Auth;
import com.uzhie.web.bean.RequestBean;
import com.uzhie.web.module.User;
import com.uzhie.util.SessionManager;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Method;

/**
 * Created by TangFei on 2018/7/16.
 * 1.鉴权 前切 只做鉴权操作，如果鉴权失败 向上抛出runtimeException
 */
public class AuthAspect {

    private Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private SessionManager<User> sessionManager;

    public void run(JoinPoint point) throws Throwable {
        logger.trace("进入 AuthAspect 环切，检验登录信息");
        MethodSignature methodSignature = (MethodSignature) point.getSignature();
        Method method = methodSignature.getMethod();
        if (method.isAnnotationPresent(Auth.class)) {
            boolean tokenRequired = method.getAnnotation(Auth.class).tokenRequired();
            if (tokenRequired) {
                // TODO: 2018/7/19 进行鉴权
                Object[] args = point.getArgs();
                RequestBean requestBean = JSONObject.parseObject(JSON.toJSONString(args[0]), RequestBean.class);
                String requestToken = requestBean.getRequestToken();
                try {
                    sessionManager.get(requestToken);
                    // 如果session校验通过 向后执行 请求参数剥离操作
                } catch (NoSuchFieldException e) {
                    logger.error("验证不通过");
                    throw new SecurityException("验证不通过", e);
                } finally {
                    logger.info("退出 AuthAspect 环切");
                }
            }
        }
    }
}
